<template>
  <div>
    <!--三级分类结构-->
    <Category :fetchCategoryId="fetchCategoryId"></Category>
    <!-- 卡片:目前是展示已有的属性与属性值的结构 -->
    <el-card shadow="always" style="margin: 20px 0px">
      <div v-show="scene == 0">
        <!-- disabled:禁用,真 禁用 假，不禁用 -->
        <el-button
          type="primary"
          size="default"
          icon="el-icon-plus"
          round
          plain
          @click="addAttr"
          :disabled="c3 ? false : true"
          >添加属性</el-button
        >
        <el-table border stripe style="margin: 20px 0px" :data="attrArr">
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="attrName" label="属性名称" width="140">
          </el-table-column>
          <el-table-column label="属性值" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                style="margin: 0px 10px"
                :type="attrValue.id % 2 == 0 ? 'success' : 'warning'"
                size="normal"
                v-for="(attrValue, index) in row.attrValueList"
                :key="attrValue.id"
                >{{ attrValue.valueName }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template slot-scope="{ row, $index }">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="考虑考虑"
                icon="el-icon-info"
                icon-color="red"
                @onConfirm="deleteAttr(row)"
                :title="`你确定删除${row.attrName}?`"
              >
                <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete" style="margin:0px 10px"></el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性|修改属性结构的地方 -->
      <div v-show="scene==1">
        <el-form ref="form" :inline="true">
          <el-form-item label="属性名" size="normal">
            <el-input
              placeholder="属性名"
              size="normal"
              v-model="attrForm.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          icon="el-icon-plus"
          :disabled="attrForm.attrName ? false : true"
          @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button size="default" @click="scene = 0">取消</el-button>
        <!-- 收集的是属性的属性值 -->
        <el-table
          border
          stripe
          style="margin: 20px 0px"
          :data="attrForm.attrValueList"
        >
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称" width="width">
            <template slot-scope="{ row, $index }">
              <!--编辑模式与查看模式切换-->
              <el-input
                :ref="$index"
                placeholder="请输入属性值"
                size="mini"
                v-model="row.valueName"
                v-if="row.visite"
                @blur="blurHandler(row)"
                @keydown.native.enter="blurHandler(row)"
              ></el-input>
              <pre v-else @click="clickHandler(row, $index)"
                >{{ row.valueName }}----{{ $index }}</pre
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="attrForm.attrValueList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          icon="el-icon-document-copy"
          :disabled="attrForm.attrValueList.length > 0 ? false : true"
          @click="save"
          >保存</el-button
        >
        <el-button size="default" @click="scene = 0">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      //控制编辑模式与查看模式切换
      c1: "",
      c2: "",
      c3: "",
      //切换底部场景的属性
      scene: 0, //0代表已有属性与属性值   1:添加或者修改
      //存储相应属性与属性值的K
      attrArr: [],
      //收集属性与属性值的参数
      attrForm: {
        attrName: "", //属性名字
        categoryId: "", //哪一个三级分类的属性
        categoryLevel: 3, //三级分类
        attrValueList: [
          // {
          //   attrId: "对应属性的ID",
          //   valueName: "属性的属性值",
          // },
        ], //收集的属性值
      },
    };
  },
  methods: {
    //获取分类的ID(一级、二级、三级)
    fetchCategoryId(id, level) {
      switch (level) {
        case 1:
          this.c1 = id;
          this.c2 = "";
          this.c3 = "";
          break;
        case 2:
          this.c2 = id;
          this.c3 = "";
          break;
        default:
          this.c3 = id;
          //在发请求之前确保一级、二级、三级ID是有的
          this.getAttrList();
          break;
      }
    },
    //封装函数,获取某一个分类的属性与属性
    async getAttrList() {
      //整理参数
      const { c1, c2, c3 } = this;
      //发请求
      let result = await this.$http.attr.reqAttr(c1, c2, c3);
      if (result.code == 200) {
        //数组的替换
        this.attrArr = result.data;
      }
    },
    //场景0添加属性按钮的回调
    addAttr() {
      //切换场景
      this.scene = 1;
      //收集参数:三级分类的ID
      //清空属性与属性值参数
      this.attrForm = {
        attrName: "",
        categoryId: this.c3,
        categoryLevel: 3,
        attrValueList: [],
      };
    },
    //添加属性值按钮的回调
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: undefined, //新增一个属性，新增的属性有ID?
        valueName: "",
        visite: true,
      });
      //需要el-input聚焦
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus();
      });
    },
    //编辑模式与切换模式失却焦点的事件
    blurHandler(row) {
      //非正常情况:属性值为空的不行的
      if (row.valueName.trim() == "") {
        this.$message("豪哥提示:属性值不能为空的");
        return;
      }

      //非正常情况:新增的属性值不能出现重的
      let repeat = this.attrForm.attrValueList.find((item) => {
        //查询数组里面是否有重复元素，前提先把自己抛出去
        if (item != row) {
          return item.valueName == row.valueName;
        }
      });

      //如果出现重复的属性值
      if (repeat) {
        this.$message("豪哥提示:属性值有重复的");
        //将重复的元素直接从数组里面移出
        this.attrForm.attrValueList.splice(
          this.attrForm.attrValueList.indexOf(row),
          1
        );
        return;
      }

      //立马隐藏el-input
      row.visite = false;
    },
    clickHandler(row, index) {
      row.visite = true;
      //获取相应的el-input组件的VC,让他聚焦
      //点击pre标签的时候,visite属性发生变化,页面要在此渲染【input】，当你点击pre的一瞬间
      //el-input组件不可能一瞬间渲染完毕，通过nextTick获取渲染完毕后的VC！！！！
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
      // setTimeout(()=>{
      //   this.$refs[index].focus();
      // },200);
    },
    //保存按钮的回调
    async save() {
      //非法情况1:已有的属性不能发请求
      //新的属性在已有属性中出现不能发请求，给个提示
      if (
        this.attrArr.find((item) => item.attrName == this.attrForm.attrName) &&
        !this.attrForm.id
      ) {
        this.$message("豪哥提示:新增的属性以存在");
        return;
      }

      //非法情况2:只要属性值有空的不能发请求
      let isAttrValueNone = this.attrForm.attrValueList.find((item) => {
        return item.valueName == "";
      });
      if (isAttrValueNone) {
        this.$message("亲睁开的你眼睛,属性值有空的请您填写完毕");
        return;
      }
      //整理参数
      //数组的替换
      this.attrForm.attrValueList = this.attrForm.attrValueList.map((item) => {
        return {
          attrId: item.attrId,
          valueName: item.valueName,
        };
      });
      //发请求
      try {
        //添加属性|修改属性成功
        let result = await this.$http.attr.reqAddOrUpdateAttr(this.attrForm);
        console.log(result);
        //提示框显示
        this.$notify({
          title: "成功",
          message: this.attrForm.id ? "修改属性成功" : "添加属性成功",
          type: "success",
        });
        //切换场景
        this.scene = 0;
        //再次获取最新的属性与属性值
        this.getAttrList();
      } catch (error) {
        //添加或者修改属性失败
      }
    },
    //修改某一个属性值
    //row,修改已有的属性
    updateAttr(row) {
      //切换场景为1
      this.scene = 1;
      //修改已有的属性与属性值:目前用的是浅拷贝，好像没问题！！！！
      this.attrForm = { ...row };
      //给已有的属性的属性值，数组里面元素追加visite属性

      //vue豪哥带的：我心有数
      //Vue检测数据【响应式数据]:数组 替换(map、filter、[]) 、变更(shift|unshift|pop|push|reverse|sort|splice)

      // this.attrForm.attrValueList.forEach(item=>{
      //        //响应式对象：动态 点语法追加属性，并非响应式的 【数据变化视图跟这边变化】
      //        //通过VC的$set方法动态追加
      //        //第一个:响应式对象  第二个参数：动态追加的属性   第三个参数：动态属性的属性值
      //        this.$set(item,"visite",false);
      // });

      //数组替换,vue可以检测到数据变化视图跟着变化
      this.attrForm.attrValueList = this.attrForm.attrValueList.map((item) => {
        return {
          ...item,
          //响应式属性
          visite: false,
        };
      });
    },
    //删除某一个属性值
    async deleteAttr(row){
       //发请求
      try {
        //删除某一个属性
        await this.$http.attr.reqDeleteAttr(row.id);
        //再次获取最新的属性的数据
        this.getAttrList();
      } catch (error) {
        
      }
    }
  },
};
</script>

<style scoped>
</style>
